package xyz.zdsoft.ask_for_leave_manage_module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.zdsoft.ask_for_leave_manage_module.bo.TeacherSearchBo;
import xyz.zdsoft.ask_for_leave_manage_module.mapper.TeacherLeavesMapper;
import xyz.zdsoft.ask_for_leave_manage_module.service.TeacherLeaveService;
import xyz.zdsoft.ask_for_leave_manage_module.vo.StudentLeaveForTeacherVo;
import xyz.zdsoft.common.entity.Leave;
import xyz.zdsoft.common.entity.LeaveOperationRecord;
import xyz.zdsoft.common.exception.BizException;
import xyz.zdsoft.common.service.impl.LeaveOperationRecordServiceImpl;
import xyz.zdsoft.common.service.impl.LeaveServiceImpl;
import xyz.zdsoft.common.utils.JwtUtils;
import xyz.zdsoft.common.utils.Result;
import xyz.zdsoft.common.utils.ResultBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 夏兵
 */
@Service
public class TeacherLeaveServiceImpl implements TeacherLeaveService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TeacherLeavesMapper teacherLeavesMapper;

    @Autowired
    private LeaveServiceImpl leaveService;

    @Autowired
    private LeaveOperationRecordServiceImpl recordService;

    @Override
    public Result<StudentLeaveForTeacherVo> queryStuLeaveForTea(TeacherSearchBo teacherSearchBo) {
        if (teacherSearchBo.getPass() == null) {
            throw new BizException("400", "必须查询审批通过或不通过");
        }

        Page<StudentLeaveForTeacherVo> page;
        if (teacherSearchBo.getCurrent() != null && teacherSearchBo.getSize() != null) {
            page = new Page<>(teacherSearchBo.getCurrent(), teacherSearchBo.getSize());
        } else {
            page = new Page<>();
        }

        QueryWrapper<StudentLeaveForTeacherVo> queryWrapper = new QueryWrapper<>();

        queryWrapper.ge(teacherSearchBo.getStartLeaveTime() != null, "submit_time",
                teacherSearchBo.getStartLeaveTime());
        queryWrapper.le(teacherSearchBo.getEndLeaveTime() != null, "submit_time",
                teacherSearchBo.getEndLeaveTime());
        queryWrapper.eq(teacherSearchBo.getCollegeId() != null, "college_id",
                teacherSearchBo.getCollegeId());
        queryWrapper.eq(teacherSearchBo.getMajorId() != null, "major_id",
                teacherSearchBo.getMajorId());
        queryWrapper.eq(teacherSearchBo.getClassId() != null, "class_id",
                teacherSearchBo.getClassId());
        queryWrapper.eq(teacherSearchBo.getGradeId() != null, "grade_id",
                teacherSearchBo.getGradeId());
        queryWrapper.eq(teacherSearchBo.getUserNo() != null, "user_no",
                teacherSearchBo.getUserNo());
        queryWrapper.like(teacherSearchBo.getStuName() != null, "stu_name",
                teacherSearchBo.getStuName());
        queryWrapper.like(teacherSearchBo.getTheme() != null, "theme",
                teacherSearchBo.getTheme());
        queryWrapper.eq(teacherSearchBo.getLeaveType() != null, "leave_type",
                teacherSearchBo.getLeaveType());

        if (teacherSearchBo.getPass() == 0 || teacherSearchBo.getStatus() == 0 || teacherSearchBo.getStatus() == 1) {
            queryWrapper.eq( "`status`", 0).or().eq("`status`", 1);
        } else if (teacherSearchBo.getPass() == 1 || teacherSearchBo.getStatus() == 2){
            queryWrapper.eq( "`status`", 2);
        }
        int teacherId;
        try {
            teacherId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        return Result.ok().data(teacherLeavesMapper.queryStuLeaveForTea(page, queryWrapper, teacherId));
    }

    @Override
    @Transactional
    public synchronized ResultBody passLeave(Integer leaveId) {
        if (leaveId == null) {
            throw new BizException("401", "请假id不能为空");
        }
        int teacherId;
        try {
            teacherId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        if (teacherId != teacherLeavesMapper.queryLeaveOfTeacher(teacherId)) {
            throw new BizException("300", "你不是该班级的班主任");
        }
        Leave leave = new Leave();
        leave.setId(leaveId);
        // 设为通过
        leave.setStatus(2);
        leaveService.updateById(leave);
        LeaveOperationRecord record = new LeaveOperationRecord();
        record.setLeaveId(leaveId);
        record.setStatus(2);
        record.setOperationTime(new Date());
        recordService.save(record);
        return ResultBody.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody eliminateLeave(Integer leaveId, String reason) {
        if (leaveId == null) {
            throw new BizException("401", "请假id不能为空");
        }
        if (StringUtils.isBlank(reason)) {
            throw new BizException("401", "不通过原因不能为空");
        }
        int teacherId;
        try {
            teacherId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        Integer teaId;
        if ((teaId = teacherLeavesMapper.queryLeaveOfTeacher(leaveId)) == null) {
            throw new BizException("300", "没找到对应的请假记录");
        }
        if (teacherId != teaId) {
            throw new BizException("300", "你不是该班级的班主任");
        }
        Leave leave = new Leave();
        leave.setId(leaveId);
        // 设为不通过
        leave.setStatus(1);
        leaveService.updateById(leave);
        LeaveOperationRecord record = new LeaveOperationRecord();
        record.setLeaveId(leaveId);
        record.setStatus(1);
        record.setOperationTime(new Date());
        record.setReasonsFailure(reason);
        recordService.save(record);
        return ResultBody.success();
    }

}
